package com.woniu.gf.pawn.config;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.DigestUtils;

public class MyCache implements Cache {
    private final String id;

    /**
     * 必须有一个构造方法
     * @param id
     */
    public MyCache(String id) {
        this.id = id;
    }

    /**
     * 返回值不能为空
     * @return
     */
    @Override
    public String getId() {

        return this.id;
    }

    /**
     * 缓存中存值
     * @param key
     * @param value
     */
    @Override
    public void putObject(Object key, Object value) {

        getRedisTemplate().opsForHash().put(this.id.toString(),getMD5(key.toString()),value);
    }

    /**
     * 缓存中取值
     * @param key
     * @return
     */
    @Override
    public Object getObject(Object key) {

        return getRedisTemplate().opsForHash().get(this.id.toString(),getMD5(key.toString()));

    }

    /**
     * 指定删除key
     * @param key
     * @return
     */
    @Override
    public Object removeObject(Object key) {
        return null;
    }

    /**
     * 当mybatis 进行增删改 清除缓存
     */
    @Override
    public void clear() {
        getRedisTemplate().delete(this.id.toString());
    }

    /**
     * 击中率
     * @return
     */
    @Override
    public int getSize() {

        return getRedisTemplate().opsForHash().size(this.id.toString()).intValue();
    }


    /**
     * 获取
     */
    public static RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUntils.getBean("redisTemplate");
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    /**
     * 优化 使用md5
     * @param key
     * @return
     */
    public static String getMD5(String key){

        return DigestUtils.md5DigestAsHex(key.getBytes());
    }
}
